package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.DefaultEditorKit.InsertBreakAction;

import com.situ.web.entity.Department;
import com.situ.web.entity.User;
import com.situ.web.util.JDBCUtil;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

import jdk.nashorn.internal.ir.BreakableNode;


public class UserServlet extends HttpServlet{

	//访问servlet时候默认访问的就是这个service方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//user?method=list&id=4
		//处理post乱码问题
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		System.out.println("method: " + method);
		switch (method) {
		case "list":
			list(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "getUserInsertPage":
			getUserInsertPage(req, resp);
			break;
		case "insert":
			insert(req, resp);
			break;
		case "toUpdate":
			toUpdate(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		default:
			break;
		}
		
	}
	
	private void getUserInsertPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//查询出所有的部门信息List<Department> list
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		ArrayList<Department> list = new ArrayList<Department>();
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,`name` FROM `department`";
			//预编译
			statement = connection.prepareStatement(sql);
			resultSet = statement.executeQuery();
			System.out.println(statement);
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				Department department = new Department(id, name);
				list.add(department);
			}

			for (Department department : list) {
				System.out.println(department);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {//不管你抛没抛出异常，finally一定会执行
			JDBCUtil.close(connection, statement, resultSet);
		}
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_insert.jsp").forward(req, resp);
	}

	//2、在user_update.jsp页面用户修改完之后，点击修改按钮这才是真正的修改。
	private void update(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		String age = req.getParameter("age");
		
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "UPDATE `user` SET `name`=?,`password`=?,age=? WHERE id=?";
			statement = connection.prepareStatement(sql);
			statement.setString(1, name);
			statement.setString(2, password);
			statement.setInt(3, Integer.parseInt(age));
			statement.setInt(4, Integer.parseInt(id));
			int count = statement.executeUpdate();
			System.out.println(statement);
			if (count == 1) {
				System.out.println("更新成功");
			} else {
				System.out.println("更新失败");
			}
			
			resp.sendRedirect("/JavaWeb1905/user?method=list");
		}  catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
	}
	

	/*
	 * 1、点击修改按钮做的操作是：根据id查询出用户的信息user，
	 * 放到req.setAttribute("user",user)，
		转发到user_update.jsp,通过${user}
	 */
	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		//select * from user where id=3;
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,`name`,password,age,department_id FROM `user` where id=?";
			//预编译
			statement = connection.prepareStatement(sql);
			statement.setInt(1, Integer.parseInt(id));
			resultSet = statement.executeQuery();
			System.out.println(statement);
			if (resultSet.next()) {
				//Duplicate local variable id
				int userId = resultSet.getInt("id");
				String name = resultSet.getString("name");
				String password = resultSet.getString("password");
				int age = resultSet.getInt("age");
				int departmentId = resultSet.getInt("department_id");
				User user = new User(userId, name, password, age, departmentId);
				//转发到user_update.jsp页面做修改
				req.setAttribute("user", user);
				req.getRequestDispatcher("/user_update.jsp").forward(req, resp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {//不管你抛没抛出异常，finally一定会执行
			JDBCUtil.close(connection, statement, resultSet);
		}
	}

	private void insert(HttpServletRequest req, HttpServletResponse resp) {
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		String age = req.getParameter("age");
		String departmentId = req.getParameter("departmentId");
		
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "INSERT INTO `user`(`name`,`password`,age,department_id)  VALUES(?,?,?,?)";
			statement = connection.prepareStatement(sql);
			statement.setString(1, name);
			statement.setString(2, password);
			statement.setInt(3, Integer.parseInt(age));
			statement.setInt(4, Integer.parseInt(departmentId));
			int count = statement.executeUpdate();
			System.out.println(statement);
			if (count == 1) {
				System.out.println("插入成功");
			} else {
				System.out.println("插入失败");
			}
			
			//重定向到列表界面/user?method=list
			resp.sendRedirect("/JavaWeb1905/user?method=list");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		System.out.println("id: " + id);
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "delete from user where id=?";
			statement = connection.prepareStatement(sql);
			statement.setInt(1, Integer.parseInt(id));
			int count = statement.executeUpdate();
			System.out.println(statement);
			if (count == 1) {
				System.out.println("删除成功");
			} else {
				System.out.println("删除失败");
			}
			
			//重定向到列表界面/user?method=list
			resp.sendRedirect("/JavaWeb1905/user?method=list");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
	}

	private void list(HttpServletRequest req, HttpServletResponse resp) {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,`name`,password,age,department_id FROM `user`";
			//预编译
			statement = connection.prepareStatement(sql);
			resultSet = statement.executeQuery();
			System.out.println(statement);
			ArrayList<User> list = new ArrayList<User>();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				String password = resultSet.getString("password");
				int age = resultSet.getInt("age");
				int departmentId = resultSet.getInt("department_id");
				User user = new User(id, name, password, age, departmentId);
				list.add(user);
			}

			for (User user : list) {
				System.out.println(user);
			}
			//转发到user_list.jsp页面展示
			//request是一个域对象，理解成一个内存区域
			//这个内存区域可以存放数据
			//在servlet查找数据，放到request中，然后转发到jsp页面展示
			req.setAttribute("list", list);
			//转发到user_list.jsp展示
			req.getRequestDispatcher("/user_list.jsp").forward(req, resp);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {//不管你抛没抛出异常，finally一定会执行
			JDBCUtil.close(connection, statement, resultSet);
		}
	}
}
